﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Threading.Tasks;
using System.Windows.Input;
using FinPlusInterfaces;
using FinPlusAssembler;

namespace FinPlusCompCore
{
    public class AuditDB : FinPlusComponent, IAuditManager 
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }
        private enum Params {From, Trigger, Audit }
        private volatile FinPlusConnectDB _audit;
        private volatile static Object _lock = new Object();
        private string _configType;

        //construct
        public AuditDB(string configType, string config, Env env)
        {
            _configType = configType;
            Config = config;
            Env = env;
        }

        //common control interface 
        public override void Dispose()
        {
            if (_audit != null)
                _audit.Dispose();
        }

        //public
        public async void SaveAudit(string trigger, IPod[] pods)
        {
            GetAudit();

            await Task.Run(() =>
            {
                var audit = IOC.New<IPod>(Params.Audit.ToString(), null, User, -1);
                audit[Common.Environment.ToString(), User] = Env.ToString();
                audit[Common.Config.ToString(), User] = Config;
                audit[Params.From.ToString(), User] = _configType;
                audit[BeanField.User.ToString(), User] = User;
                audit[Params.Trigger.ToString(), User] = trigger;

                int x = 1;
                foreach (var pod in pods)
                    audit.Add(string.Format("Link{0}", x++), pod, User,  pod.Id, -1, DateTime.MinValue);

                //_audit.Save(audit);
            });
        }
        
        //private
        private void GetAudit()
        {
            if (_audit == null)
                lock (_lock)
                    if (_audit == null)
                           _audit = new FinPlusConnectDB(Params.Audit.ToString(), "[group],Audit;[type]", QueryType.SavePod, string.Empty, ConType.All);
        }
    }
}
